<template>
 <div class="container">
<!--    <el-button @click="isEnd = !isEnd">切换</el-button>-->
   <div class="top" v-if="isEnd">
     <div class="bgc">
       <span style="color: gray;font-size: 25px">{{timer}}秒后播放下一个视频</span>
        <el-row>
          <el-col v-for="(item,index) in nextVideos" :key="item.videoId" :span="8">
            <div class="next-video-box">
              <div class="next-video-item" @click="selectItem(item.videoId,index)">
                <div>
                  <el-image :src="item.videoCover" style="width: 220px;height: 150px;border-radius: 8px"></el-image>
                </div>
                <span class="title">{{item.videoTitle}}</span>
              </div>
            </div>
          </el-col>
        </el-row>
     </div>
   </div>
   <div v-else class="top">
     <div class="video-player">
       <video autoplay @ended="handleEnd" :src="url" ref="videoPlayer" @pause="handlePause" @play="handlePlay" @timeupdate="getTimeProgress()" class="player" controls></video>
       <div class="danmaku-item" v-if="isExi" :style="item.styleObj" v-for="item in danmakuList" :key="item.id">{{item.content}}&nbsp;</div>
       <div class=""></div>
     </div>
     <div class="process-tip" v-if="msg">{{msg}}，<span style="color:#ffdada;cursor: pointer;" @click="toHeader()">从头播放？</span></div>
   </div>
   <div class="danmu-send">
     <div class="left-info">
       {{onlineCount}}人正在看，已装填{{danmakuList.length}}条弹幕
     </div>
     <div class="send-area">
       <el-input v-model="text" style="width: 300px" placeholder="请输入弹幕..."></el-input>

       <el-button type="primary" @click="sendMessage()">发送</el-button>
     </div>

   </div>
   <ul class="danmaku-list">
     <li class="list-item" v-for="(item,index) in dataList" :key="index">{{item}}</li>
   </ul>
 </div>

</template>
<script setup>
import {onMounted, onUnmounted, ref} from "vue";
import {getDanmakuList, getProgress, updateProgress} from "@/api/api.js";
import emitter from "@/utils/emitter.js";
import {ElMessage} from "element-plus";

const props = defineProps({
  videoId:{
    type:Number,
    default:35
  },

  url:{
    type:String,
    default: '{}'
  },
  moveDuration:{
    type:Number,
    default:12
  }
})

const text = ref('')

const userId = Number(localStorage.getItem("userId"))
let socket = null;
let onLineCountSocket = null
onMounted(()=>{
   onLineCountSocket = new WebSocket(`ws://localhost:8080/ws/online/${userId}/${props.videoId}`)
  initOnlineSocket(onLineCountSocket)
})

const danmakuList = ref([
  {
    id:0,
    videoId:35,
    userId:12,
    content:"我是第一条弹幕",
    // content:"",
    color:"#ff9090",
    size:16,
    position:"10",
    playTime:3,
    likeCount:0,
  }
])
const isExi = ref(false)


/* 播放位置标记 */
const toHeader = () => {
  videoPlayer.value.currentTime = 0
  msg.value = ''
}

const msg = ref() // 播放位置消息提示
/**
 * 格式化时间格式，时分秒格式化转为时分秒字符串格式
 * @param timeStamp
 * @returns {string}
 */
function formatTime(timeStamp){
  timeStamp = Math.floor(timeStamp)
  const second = Math.floor(timeStamp%60)
  const minute = Math.floor(timeStamp/60)
  console.log(second)
  console.log(minute)
  const fixSecond = second > 9 ? second:'0'+second
  const fixMinute = minute > 9 ? minute:'0'+minute
  return fixMinute + ":" + fixSecond
}


async function setLastProgress(videoId) {
  console.log("======计算上次播放位置======")
  const userId = Number(localStorage.getItem("userId"))
  console.log("开始请求")
  const res = await getProgress(userId, videoId);
  console.log("请求完成，结果为：")
  console.log(res)
  const progress = res.data
  if(progress > 5){
    console.log("开始渲染")
    msg.value = `上次播放到${formatTime(progress)}`
    videoPlayer.value.currentTime = progress
    setTimeout(() => {
      msg.value = null
    }, 5000)
  }
  console.log("======计算上次播放位置结束======")
}


const saveTime = async () => {
  console.log("======开始保存播放位置信息======")
  try {
   const timeObj = {
     videoId:props.videoId,
     userId:Number(localStorage.getItem("userId")),
     progress:Math.floor(realTime.value)-1,
   }
   await updateProgress(timeObj)
 }catch (e){
    ElMessage.error("保存播放位置失败")
 }

  console.log("======保存播放位置信息结束======")
}
/* 播放位置标记结束 */


/* 处理结束事件 */
const isEnd = ref(false)
const nextVideos = ref()
const timer = ref(5)

function playNext(nextVideoId,index = 0) {
  emitter.emit("changeNextVideo", ({nextVideoId,index}))
  isEnd.value = false
  timer.value = 5
}

function timerPlay() {
  timerObj = setInterval(() => {
    // console.log(timer.value)
    if (timer.value === 0) {
      clearInterval(timerObj)
      playNext(nextVideos.value[0].videoId);
      timer.value = 5
      // playNext()
    }
    timer.value--
  }, 1000)
}



const handleEnd = async () =>{
  const timeObj = {
    videoId:props.videoId,
    userId:Number(localStorage.getItem("userId")),
    progress:0,
  }
  // alert("casjkcnasklvhas00000000000")
  await  updateProgress(timeObj)

  // console.log(nextVideos.value)
  isEnd.value = true
  // alert("cnajkcndav")
  emitter.emit("getNextVideos",(videos)=>{
    nextVideos.value = videos.slice(0,6)
  })
  console.log(nextVideos)
  // alert(nextVideos)
  // alert(nextVideos.value[0].videoId)

  // timeOutObj = setTimeout(()=>{
  //
  // },5000)
  timerPlay();
  // alert(nextVideos+'')
}
// let timeOutObj = null
let timerObj = null
const selectItem = (videoId,index) => {
  clearInterval(timerObj)
  // clearTimeout(timeOutObj)
  timer.value = 5
  console.log("选择的索引值为："+index)
  playNext(videoId,index)
}

/* 处理结束事件结束 */



onMounted(async ()=>{
  if(userId){
    console.log("用户存在，开始加载上次播放位置...")
    await setLastProgress(props.videoId);
  }
  console.log("开始加载弹幕...")
  const res = await getDanmakuList(props.videoId)
  console.log("弹幕加载完成，结果为：")
  console.log(res.data)
  danmakuList.value = res.data
  console.log("初始化弹幕socket")
  socket = new WebSocket(`ws://localhost:8080/ws/danmaku/${props.videoId}/${userId}`)
  initWebSocket(socket)

  danmakuList.value.forEach(ele=>{
    if(ele.userId === userId){
      ele.isMine = true
    }else {
      ele.isMine = false
    }
    // ele.hasPush = false // 是否被渲染
    ele.translateX = 0
    ele.targetX = -500
    ele.styleObj = {}
  })


})

function calcTime(seconds){
  console.log("重新计算时间:",seconds)
  // isExi.value =  false
  danmakuList.value.forEach(ele=>{
    console.log(seconds)
    console.log("执行动画")
    // ele.hasPush = true
    ele.styleObj = {
      color: ele.color,
      fontSize: `${ele.size}px`,
      top: ele.position+'%',
      // animation: `danmaku-move 3s linear`
      '--delay-danmaku-':`${ele.playTime-seconds}s`
    }
  })
  // isExi.value =  true
}
function clearDanmaku(){
  danmakuList.value.forEach(ele=>{
    isExi.value = false
  })
}
function getDanmakuStyle(item){
  return {
    color: item.color,
    fontSize: `${item.size}px`,
    top: item.position,
    // 添加动画延迟（根据弹幕出现时间计算）
    // 自定义属性传递动画时间
    '--move-duration': `${props.moveDuration}s`
  }
}

const videoPlayer = ref(null)
const isPlaying = ref(false)
let first = 0
let second = 0
const getTimeProgress = () => {
  realTime.value = videoPlayer.value.currentTime
  // console.log(videoPlayer.value)
  // console.log(videoPlayer.value.currentTime)
  second = first
  first = videoPlayer.value.currentTime
  const dis = first - second
  if(dis > 2 || dis < -2){
    console.log("有人拉动进度条了")
    isExi.value = false
    console.log("重新计算每条弹幕延迟")
    // danmakuList.value.forEach(ele=>{
    //   ele.playTime = ele.playTime - videoPlayer.value.currentTime
    // })
    calcTime(videoPlayer.value.currentTime)
  }
  // console.log(isPlaying.value)
  // console.log("视频播放")
  // danmakuList.value.forEach(ele=>{
  //   if(!ele.hasPush && ele.playTime === Math.floor(videoPlayer.value.currentTime)){
  //     console.log("执行动画")
  //     ele.hasPush = true
  //     ele.styleObj = {
  //       color: ele.color,
  //       fontSize: `${ele.size}px`,
  //       top: ele.position,
  //       // animation: `danmaku-move 3s linear`
  //       '--delay-danmaku-':`${}`
  //     }
  //   }
  // })
}
let firstPlay = true
const handlePlay = () => {

  console.log("开始播放")
  isPlaying.value = true
  isExi.value = true
  console.log("弹幕预警")
  if(firstPlay){
    firstPlay = false
    calcTime(0)
  }
}
const danmakuItem = ref(null)
const handlePause = () => {
  console.log("视频暂停")
  console.log(danmakuItem.valueOf())
  isPlaying.value = false
  clearDanmaku()
}



function getData(){

}

const dataList = ref([])

let i = 2
let j = 1
const time = ref(5)
const topValue = ref(0)
function sendMessage(){
  if(!text.value.trim()){
    return
  }

  const obj = {
    videoId:props.videoId,
    userId:Number(localStorage.getItem("userId")),
    content:text.value,
    // content:"",
    // color:"#ff9090",
    color:"#000000",
    size:16,
    position:topValue.value,
    playTime:Math.round(videoPlayer.value.currentTime),
    likeCount:0,
  }
  console.log(obj)
  socket.send(JSON.stringify(obj))
  text.value = ''
  // danmakuList.value.push(obj)
}


const onlineCount = ref('')
function initWebSocket(websocket){
  websocket.onerror = function(event){
    console.log("WebSocket error")
  }

  websocket.onopen = function(event){
    console.log("WebSocket open")
  }

  websocket.onmessage = async function(event){
    console.log("接收到一条弹幕：")
    console.log(event.data)
    const data = JSON.parse(event.data)
    console.log("解析完成：")
    console.log(data)
    danmakuList.value.push(data)
    console.log(videoPlayer.value.currentTime)
    calcTime(videoPlayer.value.currentTime)
    emitter.emit("latestDanmaku",data)
  }

  websocket.onclose = function(event){
    console.log("WebSocket close")
  }
  websocket.onbeforeunload = function(event){
    websocket.close()
  }
}

function initOnlineSocket(websocket){
  websocket.onerror = function(event){
    console.log("WebSocket error")
  }

  websocket.onopen = function(event){
    console.log("WebSocket open")
  }

  websocket.onmessage = async function(event){
    console.log(event.data)
    onlineCount.value = event.data
  }

  websocket.onclose = function(event){
    console.log("WebSocket close")
  }
  websocket.onbeforeunload = function(event){
    websocket.close()
  }
}
const realTime = ref()
onUnmounted(()=>{
  console.log("卸载了")
})


window.addEventListener('unload', async function(event) {
  console.log("页面卸载了")
  await saveTime()
});

</script>
<style lang="scss" scoped>
@keyframes danmaku-move {
  from{
    transform: translateX(0);
    //transform: translateX(var(--canvas-max-width));
  }
  to{
    transform: translateX(var(--danmuku-move-dis));
  }
}
.container{

  overflow: hidden;
  //width: var(--video-container-width);height: 300px;
  width: 100%;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
  justify-content: center;
  //align-items: center;
  box-sizing: border-box;
  .danmu-send{
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 30px;
    width: 100%;
    .left-info{
      width: 300px;
      height: 30px;
      color: var(--gray-font-color--);
      font-size: 13px;
    }
    .send-area{

    }
  }
  .top{
    //width: var(--canvas-max-width);
    width: 100%;
    height: 100%;
    .bgc{
      //width: 100%;
      //height: 100%;
      height: 450px;
      width: 800px;
      box-sizing: border-box;
      padding:40px 40px;
      background-color: #252525;
      .next-video-box{
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        .next-video-item{
          width: 100%;
          box-sizing: border-box;
          .title{
            width: 220px;
            position: relative;
            top: -30px;
          }
        }
      }
    }
    position: relative;
    .process-tip{
      position: absolute;
      left: 50px;
      bottom: 80px;
      color: var(--subject-color--);
    }
    .video-player{
      width: 100%;
      height: 100%;
      position: relative;
      .player{
        width: 100%;
        //height: 100%;
      }
      .danmaku-space{
        background-color: transparent;
        position: absolute;top: 0;right: 0;
        z-index: 100;
      }
      .danmaku-item{
        color: blue;
        position: absolute;
        //left: var(--canvas-max-width)px;
        //left: var(--canvas-max-width)px;
        left: var(--canvas-max-width);
        white-space: nowrap;
        //min-width: 10px;
        max-width: var(--danmuku-max-width)px;
        animation: danmaku-move 5s linear var(--delay-danmaku-);
      }

    }
  }
}
</style>